<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { NModal, NCard, NForm, NTag, NSpace, NFormItem, NSelect, NInputNumber, NInput, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst, FormRules, DataTableColumns } from 'naive-ui'
import { useRouter } from 'vue-router'
import http from '@/tools/http'
import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'

const dictStore = useDictStore()
const userStore = useUserStore()
const router = useRouter()
const notification = useNotification()

type RowData = {
    modelId: string
    modelVersion: number
    modelName: string
    modelGroup?: string
    modelStatus?: string
    sort?: number
}

const workflowModelTableColumns: DataTableColumns<RowData> = [
    {
        title: "流程名称",
        key: "modelName",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "流程分组",
        key: "modelGroup",
        width: 100,
        ellipsis: {
            tooltip: true
        },
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("WORKFLOW_GROUP", rowData.modelGroup)
        }
    }, {
        title: "当前发布版本",
        key: "modelVersion",
        width: 110,
        render(rowData: RowData, rowIndex: number) {
            const version = rowData.modelVersion > 1 ? "V" + (rowData.modelVersion - 1) : "无"
            return h(
                NButton,
                {
                    size: "small",
                    disabled: version === "无",
                    onClick: () => openDesignWorkflowModel(rowData.modelId, rowData.modelVersion - 1, "1")
                },
                () => version
            )
        },
    }, {
        title: "流程状态",
        key: "modelStatus",
        width: 80,
        render(rowData: RowData, rowIndex: number) {
            let statusType: "default" | "error" | "primary" | "info" | "success" | "warning" = "default"
            if (rowData.modelStatus === "1") {
                statusType = "success"
            } else {
                statusType = "default"
            }
            return h(
                NTag,
                {
                    type: statusType,
                },
                () => dictStore.dictItem("WORKFLOW_MODEL_STATUS", rowData.modelStatus)
            )
        }
    }, {
        title: "操作",
        key: "actions",
        width: 260,
        fixed: 'right',
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openDesignWorkflowModel(rowData.modelId, rowData.modelVersion, "0")
                        },
                        { default: () => "设计" }
                    ),
                    rowData.modelStatus === "0" ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => updateModelStatus(rowData)
                        },
                        { default: () => "启用" }
                    ) : null,
                    rowData.modelStatus === "1" ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => updateModelStatus(rowData)
                        },
                        { default: () => "停用" }
                    ) : null,
                    h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openEditWorkflowModel(rowData)
                        },
                        { default: () => "编辑" }
                    ),
                    h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteWorkflowModel()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteWorkflowModel(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除？" }
                        }
                    )
                ]
            )
        }
    }
]

const workflowModelData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const workflowModelSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    modelName: "",
    modelGroup: undefined,
    modelStatus: undefined
})

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    modelId: "",
    modelVersion: 1,
    modelName: "",
    modelGroup: undefined,
    modelStatus: "0",
    sort: 999
})

const formRules: FormRules = ({
    modelName: {
        required: true,
        message: '请输入流程名称',
        trigger: ['input']
    },
    modelGroup: {
        required: true,
        message: '请选择流程分组',
        trigger: ['input']
    }
})

onMounted(() => {
    pageWorkflowModel()
})

function pageNumChange(pageNum: number) {
    workflowModelSearchFormValue.pageNum = pageNum
    pageWorkflowModel()
}

function pageSizeChange(pageSize: number) {
    workflowModelSearchFormValue.pageSize = pageSize
    pageWorkflowModel()
}

function openAddWorkflowModel() {
    visiable.value = true
    title.value = "添加流程模型"
    formData.modelId = ""
    formData.modelVersion = 1
    formData.modelName = ""
    formData.modelGroup = undefined
    formData.modelStatus = "0"
    formData.sort = 999
}

function openEditWorkflowModel(row: RowData) {
    visiable.value = true
    title.value = "编辑流程模型"
    formData.modelId = row.modelId
    formData.modelVersion = row.modelVersion
    formData.modelName = row.modelName
    formData.modelGroup = row.modelGroup
    formData.modelStatus = row.modelStatus
    formData.sort = row.sort
}

function openDesignWorkflowModel(modelId: string, modelVersion: number, mode: string) {
    router.push({
        name: "workflow-info",
        query: { modelId: modelId, modelVersion: modelVersion, mode: mode }
    })
}

function openDeleteWorkflowModel(row: RowData) {
    formData.modelId = row.modelId
    formData.modelVersion = row.modelVersion
    formData.modelName = row.modelName
    formData.modelGroup = row.modelGroup
    formData.modelStatus = row.modelStatus
    formData.sort = row.sort
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (title.value === "添加流程模型") {
                addWorkflowModel()
            } else {
                updateWorkflowModel()
            }
            visiable.value = false
        }
    })
}

function pageWorkflowModel() {
    http.post("/workflow/re/model/page", workflowModelSearchFormValue).then(({ data }) => {
        if (data.code === "0") {
            workflowModelData.pageNum = data.data.pageNum
            workflowModelData.pageSize = data.data.pageSize
            workflowModelData.pages = data.data.pages
            workflowModelData.total = data.data.total
            workflowModelData.list.length = 0
            for (let i = 0; i < data.data.list.length; i++) {
                workflowModelData.list.push(data.data.list[i])
            }
        }
    })
}

function addWorkflowModel() {
    http.post("/workflow/re/model/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageWorkflowModel()
        }
    })
}

function updateModelStatus(row: RowData) {
    formData.modelId = row.modelId
    formData.modelVersion = row.modelVersion
    formData.modelName = row.modelName
    formData.modelGroup = row.modelGroup
    if (row.modelStatus === "0") {
        formData.modelStatus = "1"
    }
    if (row.modelStatus === "1") {
        formData.modelStatus = "0"
    }
    formData.sort = row.sort
    http.post("/workflow/re/model/stauts/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: formData.modelStatus === "1" ? "启用成功" : "停用成功",
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageWorkflowModel()
        }
    })
}

function updateWorkflowModel() {
    http.post("/workflow/re/model/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageWorkflowModel()
        }
    })
}

function deleteWorkflowModel() {
    http.post("/workflow/re/model/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageWorkflowModel()
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="workflowModelSearchFormValue" inline label-placement="left">
                <n-form-item label="流程名称" path="modelName">
                    <n-input v-model:value="workflowModelSearchFormValue.modelName" placeholder="请输入流程名称" clearable />
                </n-form-item>
                <n-form-item label="流程分组" path="modelGroup">
                    <n-select style="width:196px" v-model:value="workflowModelSearchFormValue.modelGroup"
                        :options="dictStore.dict('WORKFLOW_GROUP')" placeholder="请选择流程分组" clearable />
                </n-form-item>
                <n-form-item label="流程状态" path="modelStatus">
                    <n-select style="width:196px" v-model:value="workflowModelSearchFormValue.modelStatus"
                        :options="dictStore.dict('WORKFLOW_MODEL_STATUS')" placeholder="请选择流程状态" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageWorkflowModel()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button attr-type="button" @click="openAddWorkflowModel()">新增</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="650" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :columns="workflowModelTableColumns" :data="workflowModelData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="workflowModelData.pageNum"
                :page-size="workflowModelData.pageSize" :item-count="workflowModelData.total"
                :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange" :on-update-page-size="pageSizeChange"
                show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 400px" :title="title">
            <n-form ref="formRef" :model="formData" :rules="formRules" label-width="78px" label-placement="left"
                require-mark-placement="left">
                <n-form-item label="流程名称" path="modelName">
                    <n-input v-model:value="formData.modelName" placeholder="请输入流程名称" clearable />
                </n-form-item>
                <n-form-item label="流程分组" path="modelGroup">
                    <n-select v-model:value="formData.modelGroup" :options="dictStore.dict('WORKFLOW_GROUP')"
                        placeholder="请输入流程分组" clearable />
                </n-form-item>
                <n-form-item label="排序" path="sort">
                    <n-input-number style="width:100%" v-model:value="formData.sort" placeholder="请输入排序" clearable />
                </n-form-item>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable = false">取消</n-button>
                    <n-button attr-type="button" @click="submit()">提交</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>